# Copyright (C) Kumo inc. and its affiliates.
# Author: Jeff.li lijippy@163.com
# All rights reserved.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.
#

###########################################################################################################################
# Here's a **well-documented English comment block** you can place at the top of your `shark_gen_cc()`
# function, including a usage example:
#
# ------------------------------------------------------------------------------
# shark_gen_cc(SOURCES HEADERS
#              [COPY]
#              NAME <name>
#              OUTPUT_DIR <dir>
#              SHARK_INCLUDE <dir>
#              SRC_PREFIX <dir>
#              PROTOS <file1.sk> [file2.sk ...]
#              [IMPORT_DIRS <dir1> <dir2> ...])
#
# Generate C++ source (.cc) and header (.h) files from Shark schema (.sk) files.
# This is an improved, parameterized version of the original Cap'n Proto/CAPN
# helper, designed for kmpkg-style reproducible builds. It ensures that schemas
# are recompiled under the current toolchain to avoid version mismatches.
#
# PARAMETERS:
#   SOURCES, HEADERS  – Output variables that will receive the generated .cc/.h files.
#
#   COPY              – (Optional) Also copy generated files back next to the
#                        original schema files. Useful if you want checked-in copies.
#
#   NAME              – Logical name for this set of generated files.
#
#   OUTPUT_DIR        – Directory where generated files will be placed.
#                        Defaults to ${CMAKE_CURRENT_BINARY_DIR}.
#
#   SHARK_INCLUDE     – Directory containing Shark's public headers (for -I flags).
#
#   SRC_PREFIX        – Source tree prefix; schema files must reside under this path
#                        so relative paths can be preserved in the output.
#
#   PROTOS            – List of .sk schema files to compile.
#
#   IMPORT_DIRS       – (Optional) Extra include directories for schema imports.
#
# NOTES:
# * The function locates `shark` and `sharkc-cpp` executables via existing
#   targets or variables. It fails with SEND_ERROR if they cannot be found.
# * Paths are normalized with get_filename_component(ABSOLUTE) to avoid issues
#   with relative paths.
# * Output files are marked GENERATED to prevent CMake from trying to scan them.
#
# EXAMPLE USAGE:
#
#   set(MY_SCHEMA_FILES
#       ${CMAKE_CURRENT_SOURCE_DIR}/proto/api1.sk
#       ${CMAKE_CURRENT_SOURCE_DIR}/proto/api2.sk)
#
#   shark_gen_cc(
#       MY_GEN_SRCS MY_GEN_HDRS
#       NAME MyApi
#       OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated
#       SHARK_INCLUDE ${PROJECT_SOURCE_DIR}/third_party/shark/include
#       SRC_PREFIX ${CMAKE_CURRENT_SOURCE_DIR}
#       PROTOS ${MY_SCHEMA_FILES}
#       IMPORT_DIRS ${PROJECT_SOURCE_DIR}/third_party/shark/schemas
#   )
#
#   add_library(myapi STATIC ${MY_GEN_SRCS} ${MY_GEN_HDRS})
#   target_include_directories(myapi PRIVATE ${CMAKE_CURRENT_BINARY_DIR}/generated)
#
# ------------------------------------------------------------------------------
###########################################################################################################################
function(shark_gen_cc SOURCES HEADERS)
    set(options
            COPY
    )
    set(args
            NAME
            OUTPUT_DIR
            SHARK_INCLUDE
            SRC_PREFIX
    )

    set(list_args
            PROTOS
            IMPORT_DIRS
    )

    cmake_parse_arguments(
            PARSE_ARGV 0
            SHARK_GEN_CC
            "${options}"
            "${args}"
            "${list_args}"
    )
    list(LENGTH SHARK_GEN_CC_PROTOS PROTO_LEN)
    if (PROTO_LEN EQUAL 0)
        message(SEND_ERROR "shark_gen_cc() called without any source files.")
    endif ()

    if(NOT SHARK_GEN_CC_NAME)
        message(SEND_ERROR "shark_gen_cc() must explicitly specify the name of the generated object by NAME")
    endif ()
    set(tool_depends ${EMPTY_STRING})
    #Use cmake targets available
    if (NOT SHARK_EXECUTABLE)
        if (TARGET shark)
            set(SHARK_EXECUTABLE $<TARGET_FILE:shark>)
        endif ()
    endif ()

    if (NOT SHARK_EXECUTABLE)
        if (TARGET shark::shark)
            set(SHARK_EXECUTABLE $<TARGET_FILE:shark::shark>)
        endif ()
    endif ()

    if (NOT SHARK_EXECUTABLE)
        message(SEND_ERROR "shark_gen_cc() Could not locate shark executable (SHARK_EXECUTABLE).")
    endif ()

    if (NOT SHARKC_CXX_EXECUTABLE)
        if (TARGET sharkc-cpp)
            set(SHARKC_CXX_EXECUTABLE $<TARGET_FILE:sharkc-cpp>)
        endif ()
    endif ()

    if (NOT SHARKC_CXX_EXECUTABLE)
        if (TARGET shark::sharkc-cpp)
            set(SHARKC_CXX_EXECUTABLE $<TARGET_FILE:shark::sharkc-cpp>)
        endif ()
    endif ()

    if (NOT SHARKC_CXX_EXECUTABLE)
        message(SEND_ERROR "shark_gen_cc() Could not locate sharkc-cpp executable (SHARKC_CXX_EXECUTABLE).")
    endif ()

    if (NOT SHARK_INCLUDE_DIRECTORY)
        if (SHARK_GEN_CC_SHARK_INCLUDE)
            set(SHARK_INCLUDE_DIRECTORY ${SHARK_GEN_CC_SHARK_INCLUDE})
        endif ()
    endif ()

    if (NOT SHARK_INCLUDE_DIRECTORY)
        if (TARGET shark)
            set(SHARK_INCLUDE_DIRECTORY ${PROJECT_SOURCE_DIR})
        endif ()
    endif ()

    if (NOT SHARK_INCLUDE_DIRECTORY)
        if (shark_INCLUDE_DIR)
            set(SHARK_INCLUDE_DIRECTORY ${shark_INCLUDE_DIR})
        endif ()
    endif ()

    if (NOT SHARK_INCLUDE_DIRECTORY)
        message(SEND_ERROR "shark_gen_cc() Could not locate shark header files (SHARK_INCLUDE_DIRECTORY).")
    endif ()

    list(APPEND tool_depends ${SHARK_EXECUTABLE} ${SHARKC_CXX_EXECUTABLE})

    if (SHARK_GEN_CC_OUTPUT_DIR)
        # Prepend a ':' to get the format for the '-o' flag right
        set(output_dir ":${SHARKC_OUTPUT_DIR}")
        set(SHARKC_OUTPUT_DIR "${SHARK_GEN_CC_OUTPUT_DIR}")
        if (NOT EXISTS "${SHARKC_OUTPUT_DIR}")
            file(MAKE_DIRECTORY "${SHARKC_OUTPUT_DIR}")
        endif ()
    else ()
        set(output_dir ":.")
        set(SHARKC_OUTPUT_DIR "${CMAKE_CURRENT_BINARY_DIR}/")
    endif ()

    if (SHARK_GEN_CC_SRC_PREFIX)
        set(SHARKC_SRC_PREFIX "${SHARK_GEN_CC_SRC_PREFIX}")
    else ()
        set(SHARKC_SRC_PREFIX "${CMAKE_CURRENT_SOURCE_DIR}")
    endif ()
    get_filename_component(SHARKC_SRC_PREFIX "${SHARKC_SRC_PREFIX}" ABSOLUTE)

    # Default compiler includes. Note that in shark's own test usage of shark_generate_cpp(), these
    # two variables will end up evaluating to the same directory. However, it's difficult to
    # deduplicate them because if SHARK_INCLUDE_DIRECTORY came from the shark_tool target property,
    # then it must be a generator expression in order to handle usages in both the build tree and the
    # install tree. This vastly overcomplicates duplication detection, so the duplication doesn't seem
    # worth fixing.
    set(include_path -I "${SHARKC_SRC_PREFIX}" -I "${SHARK_INCLUDE_DIRECTORY}")

    if (SHARK_GEN_CC_IMPORT_DIRS)
        # Append each directory as a series of '-I' flags in ${include_path}
        foreach (directory ${SHARK_GEN_CC_IMPORT_DIRS})
            get_filename_component(absolute_path "${directory}" ABSOLUTE)
            list(APPEND include_path -I "${absolute_path}")
        endforeach ()
    endif ()

    set(${SOURCES})
    set(${HEADERS})
    foreach (schema_file ${SHARK_GEN_CC_PROTOS})
        get_filename_component(file_path "${schema_file}" ABSOLUTE)
        get_filename_component(file_dir "${file_path}" PATH)
        if (NOT EXISTS "${file_path}")
            message(FATAL_ERROR "Shark Proto schema file '${file_path}' does not exist!")
        endif ()

        # Figure out where the output files will go

        # Output files are placed in SHARKC_SRC_PREFIX, at a location as if they were
        # relative to SHARKC_SRC_PREFIX.
        string(LENGTH "${SHARKC_SRC_PREFIX}" prefix_len)
        string(SUBSTRING "${file_path}" 0 ${prefix_len} output_prefix)
        if (NOT "${SHARKC_SRC_PREFIX}" STREQUAL "${output_prefix}")
            message(SEND_ERROR "Could not determine output path for '${schema_file}' ('${file_path}') with source prefix '${SHARKC_SRC_PREFIX}' into '${SHARKC_OUTPUT_DIR}'.")
        endif ()

        string(SUBSTRING "${file_path}" ${prefix_len} -1 output_path)
        set(output_base "${SHARKC_OUTPUT_DIR}/${output_path}")
        if (SHARK_GEN_CC_COPY)
            add_custom_command(
                    OUTPUT "${output_base}.cc" "${output_base}.h"
                    COMMAND "${SHARK_EXECUTABLE}"
                    ARGS compile
                    -o ${SHARKC_CXX_EXECUTABLE}${output_dir}
                    --src-prefix ${SHARKC_SRC_PREFIX}
                    ${include_path}
                    ${SHARKC_FLAGS}
                    ${file_path}
                    COMMAND cp ${output_base}.h ${file_path}.h
                    COMMAND cp ${output_base}.cc ${file_path}.cc
                    DEPENDS "${schema_file}" ${tool_depends}
                    COMMENT "Compiling Shark Proto schema ${schema_file}"
                    VERBATIM
            )
        else ()
            add_custom_command(
                    OUTPUT "${output_base}.cc" "${output_base}.h"
                    COMMAND "${SHARK_EXECUTABLE}"
                    ARGS compile
                    -o ${SHARKC_CXX_EXECUTABLE}${output_dir}
                    --src-prefix ${SHARKC_SRC_PREFIX}
                    ${include_path}
                    ${SHARKC_FLAGS}
                    ${file_path}
                    DEPENDS "${schema_file}" ${tool_depends}
                    COMMENT "Compiling Shark Proto schema ${schema_file}"
                    VERBATIM
            )
        endif ()

        list(APPEND ${SOURCES} "${output_base}.cc")
        list(APPEND ${HEADERS} "${output_base}.h")
    endforeach ()

    set_source_files_properties(${${SOURCES}} ${${HEADERS}} PROPERTIES GENERATED TRUE)
    set(${SOURCES} ${${SOURCES}} PARENT_SCOPE)
    set(${HEADERS} ${${HEADERS}} PARENT_SCOPE)
    add_custom_target(${SHARK_GEN_CC_NAME} DEPENDS ${test_sk_cpp_files} ${test_sk_h_files})
endfunction()
